package com.ibeeking.found.cop.b.rest.service.mq;

import com.ibeeking.found.cop.b.rest.service.ICopDepartmentService;
import com.ibeeking.found.cop.b.rest.service.ICopEmployeeService;
import com.ibeeking.found.cop.b.rest.service.IWxOpenService;
import com.ibeeking.found.cop.service.common.bo.CopEmployeeExtAttrBO;
import com.ibeeking.found.cop.service.common.bo.CopEmployeeExternalAttrBO;
import com.ibeeking.found.cop.service.common.bo.CopEmployeeWechatChannelBO;
import com.ibeeking.found.cop.service.common.param.CopDepartmentEmployeeParam;
import com.ibeeking.found.cop.service.common.param.CopDepartmentParam;
import com.ibeeking.found.cop.service.common.param.CopEmployeeParam;
import com.ibeeking.found.cop.service.common.param.MqSyncCopParam;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpDepartmentService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.WxCpUserService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CopContactMqConsumerHandler {

    @Resource
    private ICopDepartmentService copDepartmentServiceImpl;

    @Resource
    private ICopEmployeeService copEmployeeServiceImpl;

    @Resource
    private IWxOpenService wxOpenServiceImpl;

    public boolean syncDepartmentListFromWxcp(MqSyncCopParam mqParam, Map<String, Object> extMap) {
        try {
            Long tenantId = mqParam.getTenantId();

            WxCpService wxCpService = wxOpenServiceImpl.getWxCpService(tenantId);
            WxCpConfigStorage wxCpConfigStorage = wxCpService.getWxCpConfigStorage();
            if (wxCpConfigStorage == null) {
                throw new BusinessException("获取企微服务失败!");
            }
            WxCpDepartmentService wxCpDepartmentService = wxCpService.getDepartmentService();
            List<WxCpDepart> wxCpDeparts = wxCpDepartmentService.list(null);
            if(Collections3.isNotEmpty(wxCpDeparts)) {
                List<CopDepartmentParam> copDepartmentParams = new ArrayList<>();
                copDepartmentParams = wxCpDeparts.parallelStream().map(d -> {
                    CopDepartmentParam copDepartmentParam = new CopDepartmentParam();
                    copDepartmentParam.setId(d.getId());
                    copDepartmentParam.setName(d.getName());
                    copDepartmentParam.setNickName(StringUtils.isNotEmpty(d.getEnName())?d.getEnName():"");
                    copDepartmentParam.setTenantId(tenantId);
                    copDepartmentParam.setParentId(d.getParentId());
                    copDepartmentParam.setSort(d.getOrder());
                    return copDepartmentParam;
                }).collect(Collectors.toList());
                copDepartmentServiceImpl.saveOrUpdateOrDeleteBatchDepartment(tenantId, copDepartmentParams);
            }
            return true;
        } catch (Exception e) {
            LogUtils.error("同步部门信息任务处理异常:{}", e);
            return false;
        }
    }

    public boolean syncEmployeeListFromWxcp(MqSyncCopParam mqParam, Map<String, Object> extMap) {
        try {
            Long tenantId = mqParam.getTenantId();

            WxCpService wxCpService = wxOpenServiceImpl.getWxCpService(tenantId);
            WxCpConfigStorage wxCpConfigStorage = wxCpService.getWxCpConfigStorage();
            if (wxCpConfigStorage == null) {
                throw new BusinessException("获取企微服务失败!");
            }
            String corpId = wxCpConfigStorage.getCorpId();

            Long departmentId = mqParam.getMainDepartmentId();
            WxCpUserService wxCpUserService = wxCpService.getUserService();
            List<WxCpUser> wxCpUsers = wxCpUserService.listByDepartment(1L, true, 0);
            if(Collections3.isNotEmpty(wxCpUsers)){
                List<CopEmployeeParam> copEmployeeParamS = new ArrayList<>();
                wxCpUsers.parallelStream().forEach(d->{
                    CopEmployeeParam copEmployeeParam = new CopEmployeeParam();
                    copEmployeeParam.setTenantId(tenantId);
                    copEmployeeParam.setEmployeeCode(d.getUserId());
                    copEmployeeParam.setEmployeeName(d.getName());
                    copEmployeeParam.setNickName(d.getEnglishName());
                    copEmployeeParam.setDetailAddress(d.getAddress());
                    copEmployeeParam.setAlias(d.getAlias());
                    copEmployeeParam.setAvatar(d.getAvatar());
                    copEmployeeParam.setThumbAvatar(d.getThumbAvatar());
                    copEmployeeParam.setQrCode(d.getQrCode());
                    copEmployeeParam.setAlias(d.getAlias());
                    copEmployeeParam.setDetailAddress(d.getAddress());
                    copEmployeeParam.setEmail(d.getEmail());
                    copEmployeeParam.setBizMail(d.getBizMail());
                    if(d.getGender() !=null) {
                        copEmployeeParam.setGender(Integer.valueOf(d.getGender().getCode()));
                    }
                    if(d.getMainDepartment() !=null) {
                        copEmployeeParam.setMainDepartmentId(Long.valueOf(d.getMainDepartment()));
                        copEmployeeParam.setAsLeader(d.getIsLeader());
                    }
                    copEmployeeParam.setMobile(d.getMobile());
                    String openUserId = d.getOpenUserId();
                    if(StringUtils.isEmpty(openUserId)){
                        try{
                            String employeeCode = d.getUserId();
                            if(StringUtils.isNotEmpty(employeeCode)) {
                                Map<String, String> userOpenIdMap = wxCpUserService.userId2Openid(employeeCode, null);
                                if(userOpenIdMap!=null && userOpenIdMap.size()>0){
                                    String openId= userOpenIdMap.get("openid");
                                    if(StringUtils.isNotEmpty(openId)) {
                                        copEmployeeParam.setOpenUserId(openId);
                                    }else{
                                        copEmployeeParam.setOpenUserId(null);
                                    }
                                }else{
                                    copEmployeeParam.setOpenUserId(null);
                                }
                            }else{
                                copEmployeeParam.setOpenUserId(null);
                            }
                        }catch(WxErrorException ex){
                            copEmployeeParam.setOpenUserId(null);
                        }
                    }else {
                        copEmployeeParam.setOpenUserId(d.getOpenUserId());
                    }
                    copEmployeeParam.setPosition(d.getPosition());
                    copEmployeeParam.setTelephone(d.getTelephone());
                    copEmployeeParam.setStatus(d.getStatus());
                    copEmployeeParam.setExternalCorpName(d.getExternalCorpName());
                    if(Collections3.isNotEmpty(d.getExtAttrs())){
                        List<CopEmployeeExtAttrBO> extAttrBOS = JsonUtils.jsonToList(d.getExtAttrs(), CopEmployeeExtAttrBO.class);
                        extAttrBOS.parallelStream().forEach(g->{
                            g.setEmployeeCode(d.getUserId());
                        });
                        copEmployeeParam.setJsonExtAttr(JsonUtils.toJsonStr(d.getExtAttrs()));
                    }
                    if(Collections3.isNotEmpty(d.getExternalAttrs())){
                        List<CopEmployeeExternalAttrBO> externalAttrBOS = JsonUtils.jsonToList(d.getExternalAttrs(), CopEmployeeExternalAttrBO.class);
                        externalAttrBOS.parallelStream().forEach(g->{
                            g.setEmployeeCode(d.getUserId());
                        });
                        copEmployeeParam.setJsonExternalAttrs(JsonUtils.toJsonStr(externalAttrBOS));
                    }
                    if(d.getWechatChannels() != null){
                        CopEmployeeWechatChannelBO wechatChannelBO = BeanUtil.convertBean(d.getWechatChannels(), CopEmployeeWechatChannelBO.class);
                        wechatChannelBO.setEmployeeCode(d.getUserId());
                        copEmployeeParam.setJsonWechatChannels(JsonUtils.toJsonStr(wechatChannelBO));
                    }
                    Long[] departIds = d.getDepartIds();
                    if(departIds.length >0) {
                        List<CopDepartmentEmployeeParam> departmentEmployeeParams = new ArrayList<>();
                        Integer[] leadIds = d.getIsLeaderInDept();
                        for(int i = 0; i<  departIds.length; i++) {
                            CopDepartmentEmployeeParam departmentEmployeeParam = new CopDepartmentEmployeeParam(departIds[i],null,leadIds[i]);
                            departmentEmployeeParams.add(departmentEmployeeParam);
                        }
                        copEmployeeParam.setDepartmentEmployeeParam(departmentEmployeeParams);
                    }
                    copEmployeeParamS.add(copEmployeeParam);
                });
                copEmployeeServiceImpl.saveOrUpdateOrDeleteBatchEmployee(tenantId, copEmployeeParamS);
            }
            return true;
        } catch (Exception e) {
            LogUtils.error("同步员工信息任务处理异常:{}", e);
            return false;
        }
    }

}

